//定义js命名空间
Ext.namespace('FsCarInfo.FsCartransferDetail');
//TODO : 完善数据结构
//DateTime -- date , decimal -- float
// { name: 'Department.Name', mapping: 'Department.Name' },
// { name: 'Department'},
//FsCartransferDetail FieldArray
FsCarInfo.FsCartransferDetail.BaseFieldsArray = new Array(
	{ name: 'Id', type: 'string' },
	{ name: 'Code', mapping: 'Id' },
	{ name: 'TransferId', type: 'string' },
	{ name: 'CarId', type: 'string' },
	{ name: 'Car' },
	{ name: 'Car.Brand', mapping: 'Car.Brand' },
	{ name: 'Car.Series', mapping: 'Car.Series' },
	{ name: 'Car.Model', mapping: 'Car.Model' },
	{ name: 'Car.Color', mapping: 'Car.Color' },
	{ name: 'Car.EnginId', mapping: 'Car.EnginId' },
	{ name: 'Car.FrameId', mapping: 'Car.FrameId' },
	{ name: 'ExecUser', type: 'string' },
	{ name: 'State', type: 'string' },
	{ name: 'Version', type: 'int' },
	{ name: 'CreateTime', type: 'DateTime' }
);

//FsCartransferDetail JsonReader
FsCarInfo.FsCartransferDetail.JsonReader = Ext.extend(Infrastructure.BaseJsonReader, {
	constructor: function (cfg) {
		cfg = cfg || {};
		FsCarInfo.FsCartransferDetail.JsonReader.superclass.constructor.call(this, Ext.apply({
			fields: FsCarInfo.FsCartransferDetail.BaseFieldsArray
		}, cfg));
	}
});

//FsCartransferDetail JsonStore
FsCarInfo.FsCartransferDetail.JsonStore = Ext.extend(Infrastructure.BaseJsonStore, {
	constructor: function (cfg) {
		cfg = cfg || {};
		FsCarInfo.FsCartransferDetail.JsonStore.superclass.constructor.call(this, Ext.apply({
			url: '/FsCartransferDetail/GetPlist',
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING
			},
			remoteSort: true,
			fields: FsCarInfo.FsCartransferDetail.BaseFieldsArray,
			listeners: {
				'remove': function (thiz, record, index) {
					Ext.Ajax.request({
						url: '/FsCartransferDetail/Delete?Id=' + record.data.Id,
						success: function (response, opts) {
							var result = Ext.util.JSON.decode(response.responseText);
							if (result.success == false) {
								JsHelper.ShowError(result.msg);
								this.insert(0, record);
							}
						}
					});
				}
				/* 不自动commit
				,
				'update': function (thiz, record, type) {
				if (type == 'edit') {
				var vdata = Ext.util.JSON.encode(record.data);
				Ext.Ajax.request({
				url: '/FsCartransferDetail/SaveOrUpdate',
				params: record.data,
				success: function (response, opts) {
				var result = Ext.util.JSON.decode(response.responseText);
				if (result.success == false) {
				JsHelper.ShowError(result.msg);
				record.reject();
				} else {
				record.commit();
				}
				}
				});
				}
				}
				*/
			}
		}, cfg));
	}
});

//FsCartransferDetail GridPanel
FsCarInfo.FsCartransferDetail.EditorGridPanel = Ext.extend(Ext.grid.EditorGridPanel, {
	// User property
	//提交保存Url
	formSubmitUrl: '/FsCartransferDetail/SaveOrUpdate',
	//提交保存提示信息
	formSubmitMsg: '确定要保存吗?',
	//工具栏标签
	tbarMask: '0',
	//表格列默认显示
	columnMask: '012345600001230000090123000000',
	//调拨单ID
	transferId: '',
	//调拨记录
	transferInfo: null,

	// Property
	stripeRows: true,
	frame: true,
	border: true,
	layout: 'fit',
	loadMask: true,
	enableColumnMove: false,
	viewConfig: {
		autoFill: true
	},
	store: new FsCarInfo.FsCartransferDetail.JsonStore(),
	stateful: true,
	stateId: 'FsCarInfo.FsCartransferDetail.GridPanel',

	//constructor
	initComponent: function () {
		//prepare

		var itemGrid = this;
		var tbarMask = this.tbarMask;
		var colMask = this.columnMask;
		var cmdAddEntity = this.onAddEntity;
		var cmdDeleteEntity = this.onDeleteEntity;
		var cmdLoadEntity = this.onLoadEntity;
		var cmdQueryList = this.onQueryList;
		var cmdAfterEdit = this.onAfterEdit;
		var cmdSaveData = this.onSaveData;
		var userFunc = this.onUserFunc;
		var cmdLoadCarInfo = function (grid, rowIndex, e) {
			this.onLoadCarInfo(grid.store.getAt(rowIndex));
		}

		//set store params
		this.store.setBaseParam('transferId', this.transferId);

		//set grid tbar status
		var hideAddBtn = (this.transferInfo != null && this.transferInfo.data.State != '待提交') || this.tbarMask.charAt(0) != '1';

		// The filter.
		var gridFilter = new Ext.ux.grid.GridFilters({
			encode: true,
			filters: [
				{ dataIndex: 'Id', type: 'string' },
				{ dataIndex: 'TransferId', type: 'string' },
				{ dataIndex: 'CarId', type: 'string' },
				{ dataIndex: 'ExecUser', type: 'string' },
				{ dataIndex: 'State', type: 'string' },
				{ dataIndex: 'Version', type: 'string' },
				{ dataIndex: 'CreateTime', type: 'string' }
			]
		});

		// selModel
		var selModel = new Ext.grid.CheckboxSelectionModel({
			//header: '',
			//singleSelect: true,
			listeners: {
				'selectionchange': function (sm) {
					// 控制工具栏按钮是否可用
					itemGrid.delBtn.setDisabled(sm.getCount() < 1);
				}
			}
		});

		var stateCombo = new Ext.form.ComboBox({
			typeAhead: true,
			triggerAction: 'all',
			lazyRender: true,
			mode: 'local',
			store: new Ext.data.ArrayStore({
				id: 0,
				fields: [
					'stateId',
					'displayText'
				],
				data: [[1, '未提出'], [2, '在途'], [0, '在库']]
			}),
			valueField: 'displayText',
			displayField: 'displayText'
		});

		// columnModel 对于不常需要显示的 hidden: true 
		var gridColumn = new Ext.grid.ColumnModel({
			columns: [
				new Ext.grid.RowNumberer(),
				selModel,
				{ header: '品牌', dataIndex: 'Car.Brand' },
				{ header: '系列', dataIndex: 'Car.Series' },
				{ header: '型号', dataIndex: 'Car.Model' },
				{ header: '颜色', dataIndex: 'Car.Color' },
				{ header: '发动机号', dataIndex: 'Car.EnginId', hidden: true },
				{ header: '车架号', dataIndex: 'Car.FrameId' },
				{
					header: "执行人",
					dataIndex: 'ExecUser',
					editor: new Infrastructure.UserCombo({
						valueField: 'Name',
						editable: true,
						forceSelection: false,
						triggerAction: 'all',
						name: 'ExecUser',
						lazyRender: true,
						listClass: 'x-combo-list-small'
					})
				}, {
					header: "状态",
					dataIndex: 'State',
					editor: stateCombo
				}
			]
		});

		// PageBar
		var pagebBar = new Infrastructure.BasePagingToolbar({
			store: this.store,
			plugins: this.plugins
		});

		// 常用工具栏
		var toolBar = [{
			xtype: "tbbutton",
			minWidth: 80,
			ref: '../saveBtn',
			text: "保存",
			disabled: true,
			cls: "x-btn-text-icon",
			icon: "/Content/icons/report_disk.png",
			handler: cmdSaveData,
			scope: this
		}, {
			xtype: 'tbseparator'
		}, {
			xtype: 'textfield',
			width: 150,
			id: 'q_query',
			listeners: {
				specialkey: function (field, e) {
					if (e.getKey() == e.ENTER) {
						field.ownerCt.ownerCt.onAddEntity();
					}
				}
			}
		}, {
			xtype: 'tbaraddbtn',
			hidden: tbarMask.substring(0, 1) != '1',
			handler: cmdAddEntity,
			scope: itemGrid
		}, {
			hidden: tbarMask.substring(0, 1) != '1',
			xtype: 'tbseparator'
		}, {
			xtype: 'tbardelbtn',
			hidden: tbarMask.substring(0, 1) != '1',
			handler: cmdDeleteEntity,
			scope: itemGrid
		}, '-'];

		Ext.apply(this, {
			plugins: [gridFilter],
			sm: selModel,
			cm: gridColumn,
			tbar: toolBar,
			bbar: pagebBar,
			clicksToEdit: 1,
			listeners: {
				'afteredit': cmdAfterEdit,
				'rowdblclick': cmdLoadCarInfo
			}
		});

		FsCarInfo.FsCartransferDetail.EditorGridPanel.superclass.initComponent.call(this);
	},

	/****************** 
	* user function 
	******************/

	// 添加
	onAddEntity: function () {
		var itemGrid = this;
		var q_query = Ext.getCmp('q_query').getValue();
		//加载进度条
		Ext.MessageBox.show({
			msg: '正在提交数据到中心服务器...',
			progressText: '保存数据...',
			width: 300,
			wait: true,
			waitConfig: { interval: 1000 }
		});
		//后台添加数据
		Ext.Ajax.request({
			url: '/FsCartransferDetail/AddByCarInfo',
			params: {
				TransferId: this.transferId,
				car_query: q_query
			},
			success: function (response, opts) {
				Ext.MessageBox.hide();
				var result = Ext.util.JSON.decode(response.responseText);
				if (result.success == false) {
					JsHelper.ShowError(result.msg);
				} else {
					itemGrid.store.reload();
				}
			},
			failure: function (form, action) {
				Ext.MessageBox.hide();
				JsHelper.ShowError(action.result.msg);
			}
		});
	},

	// 读取车俩信息
	// 读取车辆信息显示
	onLoadCarInfo: function (selRecord) {
		var selId = selRecord.data.Id;
		var carStore = new FsCarInfo.FsCarbaseinfo.JsonStore();
		var carRecord = new carStore.recordType(selRecord.data.Car);

		var carInfoWin = new FsCarInfo.FsCarbaseinfo.InfoWin({
			dataRecord: carRecord,
			submitUrl: ''
		});

		carInfoWin.show();
		//itemCarInfoForm.form.loadRecord(carRecord);
	},

	// 读取信息显示
	onLoadEntity: function () {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('请选择记录编辑..');
			return -1;
		}
		var selId = selRecord.data.Id;
		var itemEditForm = new FsCarInfo.FsCartransferDetail.EditForm({
			Id: selId,
			dataRecord: selRecord,
			submitUrl: this.formSubmitUrl,
			submitMsg: this.formSubmitMsg,
			waitMsg: '数据加载中...',
			listeners: {
				'afterSave': function (ele, rt) {
					if (rt) {
						itemGrid.store.reload();
						JsHelper.ShowInfo('信息更新成功!');
					}
				}
			}
		});
		var itemEditWin = new FsCarInfo.FsCartransferDetail.EditWin({
			items: [itemEditForm]
		});
		itemEditWin.show();
		itemEditForm.form.loadRecord(selRecord);
	},

	// 删除
	onDeleteEntity: function () {
		var itemGrid = this;
		var itemGridStore = this.store;
		JsHelper.DelConfirm(function (btn) {
			if (btn == 'yes') {
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					itemGridStore.remove(r);
				}
			}
		});
	},

	// 查询
	onQueryList: function () {
		var itemGrid = this;
		var q_query = Ext.getCmp('q_query').getValue();
		itemGrid.store.load({
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING,
				q_query: q_query
			}
		})
	},

	//编辑记录信息
	onAfterEdit: function (e) {
		//var itemGrid = this;
		this.saveBtn.setDisabled(false);
	},

	//保存数据
	onSaveData: function () {
		var vRecords = this.store.getModifiedRecords(); //得到修改的数据（记录对象）
		var vCount = vRecords.length; //得到记录长度
		if (vCount > 0) {
			//begin 将记录对象转换为字符串（json格式的字符串）
			var vDatas = '[';
			for (var i = 0; i < vCount; i++) {
				vDatas += Ext.util.JSON.encode(vRecords[i].data) + ',';
			}
			vDatas = vDatas.substr(0, vDatas.length - 1) + ']';
			//end 将记录对象转换为字符串（json格式的字符串）
			var vLoadMask = new Ext.LoadMask(Ext.getBody(), { msg: '正在保存，请稍后...' });
			vLoadMask.show(); //显示遮罩窗口

			Ext.Ajax.request({
				url: '/FsCartransferDetail/SaveEditRecord',
				method: 'POST',
				params: { datas: vDatas },
				timeout: 60,
				scope: this,
				success: function (response) {
					vLoadMask.hide(); //关闭遮罩窗口
					var vResponse = eval('(' + response.responseText + ')');
					if (vResponse.success) {
						this.store.commitChanges(); //还原数据修改提示
					} else {
						Ext.MessageBox.show({
							title: '标题',
							msg: vResponse.message,
							buttons: Ext.MessageBox.OK,
							icon: Ext.MessageBox.ERROR
						});
					}
				},
				failure: function (response) {
					vLoadMask.hide(); //关闭遮罩窗口
					Ext.MessageBox.show({
						title: '标题',
						msg: response.responseText,
						buttons: Ext.MessageBox.OK,
						icon: Ext.MessageBox.ERROR
					});
				}
			});
		}
	},

	// 测试..
	onUserFunc: function () {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('未选择记录.');
			return -1;
		}
		var selId = selRecord.data.Id;
		JsHelper.Confirm('确定要提交吗?', function (btn) {
			if (btn == 'yes') {
				var ids = [];
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					ids.push(r.data.Id);
				}
				//加载进度条
				Ext.MessageBox.show({
					msg: '正在提交数据到中心服务器...',
					progressText: '保存数据...',
					width: 300,
					wait: true,
					waitConfig: { interval: 1000 }
				});
				Ext.Ajax.request({
					url: '/FsCartransferDetail/Approve',
					params: {
						'Ids': ids.toString()
					},
					success: function (response, opts) {
						Ext.MessageBox.hide();
						var result = Ext.util.JSON.decode(response.responseText);
						if (result.success == false) {
							JsHelper.ShowError(result.msg);
						} else {
							itemGrid.store.reload();
							Ext.Msg.alert('提示', '您的信息已提交，请等待处理。');
						}
					},
					failure: function (form, action) {
						Ext.MessageBox.hide();
						JsHelper.ShowError(action.result.msg);
					}
				});
			}
		});
	}
});

//FsCartransferDetail EditForm
FsCarInfo.FsCartransferDetail.EditForm = Ext.extend(Infrastructure.BaseForm, {
	Id: null,
	dataRecord: null,
	submitUrl: '/FsCartransferDetail/SaveOrUpdate',
	submitMsg: '确定要保存吗?',

	initComponent: function () {
		var itemEditForm = this;
		var cmdUpdate = this.onSave;

		//Form第一列
		// 定义表单列
		var firstColumn = [{
			fieldLabel: "调拨单ID",
			width: 150,
			maxLength: 36,
			xtype: 'textfield',
			name: 'TransferId'
		}, {
			fieldLabel: "车辆ID",
			width: 150,
			maxLength: 36,
			xtype: 'textfield',
			name: 'CarId'
		}, {
			fieldLabel: "执行人",
			width: 150,
			maxLength: 36,
			xtype: 'textfield',
			name: 'ExecUser'
		}, {
			fieldLabel: "状态",
			width: 150,
			maxLength: 10,
			xtype: 'textfield',
			name: 'State'
		}, ];

		//Form第二列
		var secondColumn = [{
			fieldLabel: 'Column2',
			readOnly: true,
			width: 150
		}];

		//Form单列
		var singleColumn = [{
			xtype: 'textarea',
			fieldLabel: '描述',
			name: 'Description',
			height: 50,
			width: 430
		}];

		Ext.apply(this, {
			items: [{
				layout: 'column',
				// 注意 现在使用的是两列 要是三列或更多
				// 请改变下面的items
				// 并在上面定义每个列的组件集合
				items: [{
					columnWidth: .5,
					bodyStyle: 'padding:1px',
					layout: 'form',
					defaultType: 'textfield',
					items: firstColumn
				}, {
					columnWidth: .5,
					bodyStyle: 'padding:1px',
					layout: 'form',
					defaultType: 'textfield',
					items: secondColumn
				}]
			}, singleColumn],
			buttons: [{
				xtype: 'btnsubmit',
				handler: cmdUpdate,
				hidden: this.submitUrl == '',
				scope: itemEditForm
			}, {
				xtype: 'btncancle',
				handler: function () {
					itemEditForm.ownerCt.destroy();
				}
			}],
			reader: new FsCarInfo.FsCartransferDetail.JsonReader()
		});

		FsCarInfo.FsCartransferDetail.EditForm.superclass.initComponent.call(this);

		//定义保存后执行的事件
		this.addEvents('afterSave');
	},

	/****************** 
	* user function 
	******************/

	//更新保存信息
	onSave: function () {
		var itemForm = this;
		var id = this.Id;
		var saveUrl = this.submitUrl;
		if (itemForm.getForm().isValid()) {
			JsHelper.Confirm(this.submitMsg, function (btn) {
				if (btn != 'no') {
					itemForm.getForm().submit({
						waitMsg: '正在提交....',
						url: saveUrl,
						params: {
							'Id': (id == null) ? '' : id
						},
						success: function (form, action) {
							//返回结果后触发保存事件
							itemForm.fireEvent('afterSave', itemForm, true);
						},
						failure: function (form, action) {
							JsHelper.ShowError(action.result.msg);
						}
					});
				}
			});
		}
	}
});

//FsCartransferDetail DetailWin
FsCarInfo.FsCartransferDetail.EditWin = Ext.extend(Ext.Window, {
	title: '车辆调拨单信息',
	iconCls: 'application_form',
	width: 600,
	resizable: false,
	constrain: true,
	autoHeight: true,
	modal: true,
	closeAction: 'close',
	plain: true,
	buttonAlign: 'center',

	//constructor
	initComponent: function () {
		FsCarInfo.FsCartransferDetail.EditWin.superclass.initComponent.call(this);
	}
});
